package com.huterox.second.utils;
import com.huterox.second.dao.message.MessageSend;
import com.huterox.second.dao.message.ResultMessage;
import com.huterox.second.dao.pojo.Message;
import com.huterox.second.server.MessageService;
import com.huterox.second.server.TalkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


@Component
public class LoadMessageUtils {
    //这个玩意主要是拿过来返回消息列表的，方便加载
//    加载的消息有两方面，一个是你自己和别人说的，另一个是别人跟你说的，所以需要两个查询
    private static TalkService talkService;
    private static MessageService messageService;
    @Autowired
    public void setTalkService(TalkService talkService){
        LoadMessageUtils.talkService = talkService;
    }
    @Autowired
    public void setMessageService(MessageService messageService){

        LoadMessageUtils.messageService = messageService;
    }

    public static List<ResultMessage> LoadMessages(Long mytalk,Long shetalk,
                                                   String myName,String sheName){

//        我们的写操作要比读操作更多，所以不用CopyOnWriteArrayList<>();
        List<ResultMessage> resultMessages= Collections.synchronizedList(new ArrayList<ResultMessage>());
        Long mytalkID = talkService.getTalkId(mytalk,shetalk);
        Long shetalkID = talkService.getTalkId(shetalk,mytalk);

        if(mytalkID!=null){
            addMessages(mytalkID,resultMessages,myName,sheName,mytalk,shetalk);
        }
        if (shetalkID!=null){
            addMessages(shetalkID,resultMessages,sheName,myName,shetalk,mytalk);
        }

        return resultMessages;
    }

    private static void addMessages(Long talkID,List<ResultMessage> LoadMessages,
                                    String fromName,String toName,Long mytalk,Long shetalk){
        List<Message> messagesByTalkID = messageService.getMessagesByTalkID(talkID);
        for (Message message : messagesByTalkID) {
            ResultMessage resultMessage_ = new ResultMessage();
            MessageSend messageSend_ = new MessageSend();
            resultMessage_.setFromID(mytalk);
            resultMessage_.setFromName(fromName);
            messageSend_.setMessage(message.getMessage());
            messageSend_.setToID(shetalk);
            messageSend_.setToName(toName);
            resultMessage_.setMessage(messageSend_);
            LoadMessages.add(resultMessage_);
        }

    }
}
